<?php

/**
 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */

namespace app\mobile\controller;


use app\admin\model\ActivityInvitationLog;
use app\admin\model\ConsumerClaimLog;
use app\admin\model\CouponConsumer;
use app\admin\model\CouponOrder;
use app\admin\model\DonateLog;
use app\BaseController;
use think\App;


/**
 * 用户操作
 *
 * @author Administrator
 *
 */
class Coupon extends BaseController
{

    public function couponList(){
        $request = $this->request;
        $param = $request->param();
        $where[] = ['is_delete','=',0];

        $where[] = ['start_time','<',time()];
        $where[] = ['end_time','>',time()];
     //   $where[] = ['status','=',2];
        $where[]= ['platformInfo.expiration_time','>',time()];

        if (isset( $param['status']) &&  $param['status']){
            $where[] = ['coupon.status','=',$param['status']];
        }
        $where[] = ['platform_id','=', $request->platform_id];
        if (isset( $param['name']) &&  $param['name']){
            $where[] = ['coupon.name','like',"%{$param['name']}%"];
        }

        if (isset( $param['store_id']) &&  $param['store_id']) {
            if (isset($param['join_status']) && $param['join_status']) {
                $couponConsumerModel = new  CouponConsumer();
                if ($param['join_status'] == 1) { // 等待加入
                    $couponConsumerList = $couponConsumerModel
                        ->where(['store_id' => $param['store_id'],'is_delete' => 0])->select()->toArray();
                    if ($couponConsumerList) {
                        $couponId = array_column($couponConsumerList, 'coupon_id');
                        $where[] = ['coupon.id', 'not in', $couponId];
                    }
                } elseif ($param['join_status'] == 2) { // 审核通过

                    $couponConsumerList = $couponConsumerModel
                        ->where(['store_id' => $param['store_id'],'is_delete' => 0])
                        ->where(['status' => 2])
                        ->select()->toArray();
                    if ($couponConsumerList) {
                        $couponId = array_column($couponConsumerList, 'coupon_id');
                        $where[] = ['coupon.id', 'in', $couponId];
                    }else{
                        $where[] = ['coupon.id', 'in', [0]];
                    }
                }elseif ($param['join_status'] == 3){ // 待审核
                    $couponConsumerList = $couponConsumerModel
                        ->where(['store_id' => $param['store_id'],'is_delete' => 0])
                        ->where(['status' => 1])
                        ->select()->toArray();
                    if ($couponConsumerList) {
                        $couponId = array_column($couponConsumerList, 'coupon_id');
                        $where[] = ['coupon.id', 'in', $couponId];
                    }else{
                        $where[] = ['coupon.id', 'in', [0]];
                    }
                }elseif ($param['join_status'] == 4){
                    $couponConsumerList = $couponConsumerModel
                        ->where(['store_id' => $param['store_id'],'is_delete' => 0])
                        ->where(['status' => 3])
                        ->select()->toArray();
                    if ($couponConsumerList) {
                        $couponId = array_column($couponConsumerList, 'coupon_id');
                        $where[] = ['coupon.id', 'in', $couponId];
                    }else{
                        $where[] = ['coupon.id', 'in', [0]];
                    }
                }
            }
        }
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $couponModel = new \app\admin\model\Coupon();
        $total = $couponModel
            ->withJoin(['platformInfo'], 'LEFT')->where($where)->count();

        if ($total) {
            $list = $couponModel
                ->withJoin(['platformInfo'], 'LEFT')
                ->where($where)->order('create_time', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
            foreach ($list as  $key => $value){
                $couponConsumerModel = new CouponConsumer();
                $couponConsumerList =  $couponConsumerModel->where(['coupon_id'=> $value['id'],'status' => 2])->select()->toArray();
                $consumerId  = array_column($couponConsumerList,'consumer_id');
                $ConsumerModel = new \app\admin\model\Consumer();
                $list[$key]['start_time'] = date("Y-m-d",$value['start_time']);
                $list[$key]['end_time'] = date("Y-m-d",$value['end_time']);
                $list[$key]['total_sales'] =$value['sales'] +$value['real_sales'] ;
                $list[$key]['consumer'] = $ConsumerModel->where('id','in',$consumerId)->select();

            }


        } else {
            $list = array();
        }

        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function waitCouponList(){
        $request = $this->request;
        $param = $request->param();
        $where[] = ['is_delete','=',0];

        $where[] = ['start_time','>',time()];

        $where[] = ['platform_id','=', $request->platform_id];
        if (isset( $param['name']) &&  $param['name']){
            $where[] = ['name','like',"%{$param['name']}%"];
        }
//        if (isset( $param['status']) &&  $param['status']){
//            $where[] = ['status','= ',$param['status']];
//        }
        $where[] = ['status','=',1];
        $couponConsumer = new CouponConsumer();
        $couponConsumerList = $couponConsumer->where(['store_id' => $param['store_id']])
            ->where(['status','in',1,2])->select()->toArray();
        if ($couponConsumerList){
            $couponId = array_column($couponConsumerList,'coupon_id');
            $where[] = ['in','not in ',$couponId];
        }

        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $couponModel = new \app\admin\model\Coupon();
        $total = $couponModel->where($where)->count();
        if ($total) {
            $list = $couponModel
                ->where($where)->order('create_time', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
            foreach ($list as  $key => $value){
                $couponConsumerModel = new CouponConsumer();
                $couponConsumerList =  $couponConsumerModel->where(['coupon_id'=> $value['id']])->select()->toArray();
                $consumerId  = array_column($couponConsumerList,'consumer_id');
                $ConsumerModel = new \app\admin\model\Consumer();
                $list[$key]['start_time'] = date("Y-m-d",$value['start_time']);
                $list[$key]['end_time'] = date("Y-m-d",$value['end_time']);
                $list[$key]['consumer'] = $ConsumerModel->where('id','in',$consumerId)->select();

            }


        } else {
            $list = array();
        }
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }


    public function couponConsumer(){
        $request = $this->request;
        $param = $request->param();
        $couponConsumerModel = new CouponConsumer();

        if (isset($param['store_id']) && $param['store_id']){
            $where[] = ['coupon_consumer.store_id','=',$param['store_id']];
        }
        if (isset($param['status']) && $param['status']){
            $where[] = ['coupon_consumer.status','=',$param['status']];
        }

        if (isset($param['id']) && $param['id']){
            $where[] = ['coupon_consumer.coupon_id','=',$param['id']];
        }

        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $couponConsumerModel
            ->withJoin(['consumerInfo','storeInfo'], 'LEFT')
            ->where($where)->count();
        if ($total) {
            $list = $couponConsumerModel
                ->withJoin(['consumerInfo','storeInfo'], 'LEFT')
                ->where($where)
                ->order('create_time', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();;
        } else {
            $list = array();
        }
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function buyCoupon(){
      try{

            $request = $this->request;
            $param = $request->param();
            $couponModel = new \app\admin\model\Coupon();
            $couponInfo = $couponModel->where(['id' =>$param['id'] ])->find();
            if ($couponInfo['inventory'] <= 0){
                return result(-1, '库存不足' );
            }
            $data = [
                'uid' => $param['uid'],
                'order_number' => getPayNo('cou'),
                'platform_id' => $request->platform_id,
                'coupon_id' => $param['id'],
                'pay_status' => 1,
                'price' => $couponInfo['price'],

            ];
            $couponOrderModel = new CouponOrder();
            $couponOrderModel->save($data);
            if ($couponInfo['price'] > 0){
                return result(0, '待支付', ['id' =>$couponOrderModel['id'] ,'code'=> 1 ]);
            }else{
                $couponConsumerModel = new \app\admin\model\CouponConsumer();
                $couponConsumerList = $couponConsumerModel->where(['coupon_id' =>$param['id'] ])->select();
                foreach ($couponConsumerList as $value){
                    $consumerModel = new \app\admin\model\Consumer();
                    $consumerClaimLog = new ConsumerClaimLog();
                    $consumerInfo = $consumerModel->where(['id' =>  $value['consumer_id']])->find();
                    $couponConsumerData = [
                        'order_number' => $data['order_number'],
                        'consumer_id' => $value['consumer_id'],
                        'store_id'  => $value['store_id'],
                        'platform_id'  => $request->platform_id,
                        'uid' => $param['uid'],
                        'type'=> 2,
                        'status'=> 1,
                        'expire_time' => time()+ ($consumerInfo['expire_time'] *86400 ),
                        'price' =>0,
                        'consumer_type' => $consumerInfo['consumer_type'],
                        'satisfy_amount' => $consumerInfo['satisfy_amount'],
                        'deductible_amount' => $consumerInfo['deductible_amount'],
                        'coupon_id' => $param['id'],
                        'order_id' => $couponOrderModel->id,
                        'issue_type' => $consumerInfo['issue_type'],
                        'send_way' => 3,
                        'write_store_id' =>  $value['store_id'],
                        'verification_code' =>consumerVerificationCode()
                    ];
                    $consumerClaimLog->save($couponConsumerData);
                    $settlement_code  = common_qr_code($consumerClaimLog->id.'&'.'1','consumer', $request->platform_id);
                    $consumerClaimLog->where(['id' => $consumerClaimLog->id])->update(['settlement_code' =>$settlement_code ]);

                    $consumerModel->where(['id' => $value['consumer_id']])->inc('claimed_number')->update();
                }
                $couponOrderModel->where(['id' => $couponOrderModel->id])->update(['pay_status' => 2]);

                $couponModel->where(['id' =>$param['id'] ])->inc('real_sales')->dec('inventory')->update();
                return result(0, '购买成功', ['id' =>$couponOrderModel['id'], 'code'=> 0]);

            }
        }catch (\Exception $exception){
            return result(-1, '失败' );
      }

    }

    public function couponOrder(){
        $request = $this->request;
        $param = $request->param();
        $couponOrderModel = new \app\admin\model\CouponOrder();
    //    $where[]  =[ 'platform_id' ,'=', $request->platform_id];
        $where[]  = ['uid' ,'=', $param['uid']];
        $where[]  = ['pay_status' ,'=', 2];
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $couponOrderModel  ->withJoin('couponInfo', 'LEFT')->where($where)->count();
        if ($total) {
            $list = $couponOrderModel
                ->withJoin('couponInfo', 'LEFT')
                ->where($where)->order('create_time', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
        } else {
            $list = array();
        }
        foreach ($list as $key  => $value){
//            $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
//            $consumerList = $consumerClaimLogModel->withJoin([
//                'consumerInfo'
//            ], 'LEFT')
//                ->where(['order_id' => $value['id'],'send_way' => '3'])
//                ->select();
//            $list[$key]['consumer_list'] =$consumerList;
//            $list[$key]['consumer_count'] = count($consumerList);

            $couponConsumerModel = new CouponConsumer();
            $couponConsumerList =  $couponConsumerModel->where(['coupon_id' =>$value['coupon_id'] ])->select()->toArray();
            $consumerId =[];
           if ($couponConsumerList){
               $consumerId = array_column($couponConsumerList,'consumer_id');
           }
           if ($consumerId){
               $ConsumerModel = new \app\admin\model\Consumer();
               $ConsumerList = $ConsumerModel->where('id','in',$consumerId)->select();
               $list[$key]['consumer_list'] =$ConsumerList;
               $list[$key]['consumer_count'] = count($ConsumerList);
           }else{
               $list[$key]['consumer_list'] =[];
               $list[$key]['consumer_count'] = 0;
           }

        }

        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function couponInfo(){
        $request = $this->request;
        $param = $request->param();
        $couponModel = new \app\admin\model\Coupon();
        $couponInfo = $couponModel
            ->where(['id' =>$param['id'] ])->find();
        $couponConsumerModel = new CouponConsumer();
        $couponConsumerList =  $couponConsumerModel
            ->where(['coupon_id'=> $param['id'],'is_delete' => 0,'status' =>2])->select()->toArray();
        $consumerId =[];
        if ($couponConsumerList){
            $consumerId  = array_column($couponConsumerList,'consumer_id');
        }

        $ConsumerModel = new \app\admin\model\Consumer();
        $couponInfo['start_time'] = date("Y-m-d",$couponInfo['start_time']);
        $couponInfo['end_time'] = date("Y-m-d",$couponInfo['end_time']);
        $consumerList  = $ConsumerModel
            ->withJoin(['storeInfo'
            ], 'LEFT')
            ->where('consumer.id','in',$consumerId)->select();
        foreach ($consumerList as $consumerKey => $consumerValue){
            $consumerList[$consumerKey]['expire_time'] = date('Y-m-d',$consumerValue['expire_time']);
        }
        $CouponOrderModel = new \app\admin\model\CouponOrder();
        $couponInfo['is_buy'] = 0;
        $couponInfo['total_sales'] = $couponInfo['sales'] +$couponInfo['real_sales'] ;
        if (isset($param['uid']) &&$param['uid'] ){
            $CouponOrderInfo =  $CouponOrderModel->where(['uid' =>$param['uid'] ,'coupon_id' => $param['id'],'pay_status' => 2 ])->find();
            if ($CouponOrderInfo){
                $couponInfo['is_buy'] = 1;
            }
        }

        $couponInfo['consumer'] = $consumerList;
        $couponInfo['is_join']  = 1;
        if (isset($param['store_id']) &&$param['store_id'] ){
            $storeJoinCouponInfo =   $couponConsumerModel ->where(['store_id' => $param['store_id'],'coupon_id' => $couponInfo['id']])->find();
            if ($storeJoinCouponInfo){
                if ($storeJoinCouponInfo['status'] == 2){
                    $couponInfo['is_join']  = 2;
                }else if ($storeJoinCouponInfo['status'] == 1){
                    $couponInfo['is_join']  = 3;
                }else {
                    $couponInfo['is_join']  = 4;
                }
            }
        }
        return result(0, '操作成功',$couponInfo);
    }

    public function  joinCoupon(){
        $request = $this->request;
        $param = $request->param();
        $data = [
            'store_id' => $param['store_id'],
            'coupon_id' => $param['coupon_id'],
            'consumer_id' => $param['consumer_id'],
            'platform_id'=> $request->platform_id,
            'status' => 1,
        ];
        $couponConsumer = new CouponConsumer();
        $couponConsumerInfo = $couponConsumer->where(['store_id' => $param['store_id'],'coupon_id' => $param['coupon_id'],'is_delete' => 0])->find();

        if ($couponConsumerInfo){
            if ($couponConsumerInfo['status'] == 1){
                return result(0, '已申请，等待审核中');
            }
            if ($couponConsumerInfo['status'] == 2){
                return result(0, '已加入请勿重复加入');
            }
        }

        if (isset($param['id']) && $param['id']){
            $couponConsumer->where(['id' => $param['id']])->update($data);
        }else{
            $couponConsumer->save($data);
        }

        return result(0, '申请成功,等待审核');
    }


    public function joinCouponLog(){
        $request = $this->request;
        $param = $request->param();
        $where[] = ['coupon_consumer.status','=',$param['status']];
        $where[] = ['coupon_consumer.store_id','=',$param['store_id']];
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $couponConsumer = new CouponConsumer();
        $total = $couponConsumer->withJoin(['couponInfo','consumerInfo'], 'LEFT')
            ->where($where)->count();;
        if ($total) {
            $list = $couponConsumer->withJoin(['couponInfo','consumerInfo'], 'LEFT')
                ->where($where)->order('create_time', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();


        } else {
            $list = array();
        }
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }












}